import React from 'react';
import {
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  TablePagination,
  TableSortLabel,
  Box,
  CircularProgress,
} from '@mui/material';
import { visuallyHidden } from '@mui/utils';

export interface Column<T> {
  title: string;
  dataIndex: string;
  key: string;
  sorter?: boolean;
  render?: (text: any, record: T) => React.ReactNode;
}

export interface MuiTableProps<T> {
  columns: Column<T>[];
  dataSource: T[];
  loading?: boolean;
  pagination?: {
    current: number;
    pageSize: number;
    total: number;
    onChange: (page: number, pageSize: number) => void;
  };
}

export function MuiTable<T>({
  columns,
  dataSource,
  loading = false,
  pagination,
}: MuiTableProps<T>) {
  const [order, setOrder] = React.useState<'asc' | 'desc'>('asc');
  const [orderBy, setOrderBy] = React.useState<string>('');

  const handleRequestSort = (property: string) => {
    const isAsc = orderBy === property && order === 'asc';
    setOrder(isAsc ? 'desc' : 'asc');
    setOrderBy(property);
  };

  const renderCellContent = (value: any, row: T, column: Column<T>) => {
    if (column.render) {
      return column.render(value, row);
    }
    return String(value ?? '');
  };

  return (
    <Paper sx={{ width: '100%', overflow: 'hidden' }}>
      <TableContainer>
        <Table stickyHeader aria-label="sticky table">
          <TableHead>
            <TableRow>
              {columns.map((column) => (
                <TableCell
                  key={column.key}
                  sortDirection={orderBy === column.dataIndex ? order : false}
                >
                  {column.sorter ? (
                    <TableSortLabel
                      active={orderBy === column.dataIndex}
                      direction={orderBy === column.dataIndex ? order : 'asc'}
                      onClick={() => handleRequestSort(column.dataIndex)}
                    >
                      {column.title}
                      {orderBy === column.dataIndex ? (
                        <Box component="span" sx={visuallyHidden}>
                          {order === 'desc' ? 'sorted descending' : 'sorted ascending'}
                        </Box>
                      ) : null}
                    </TableSortLabel>
                  ) : (
                    column.title
                  )}
                </TableCell>
              ))}
            </TableRow>
          </TableHead>
          <TableBody>
            {loading ? (
              <TableRow>
                <TableCell colSpan={columns.length} align="center">
                  <CircularProgress />
                </TableCell>
              </TableRow>
            ) : (
              dataSource.map((row, index) => (
                <TableRow hover role="checkbox" tabIndex={-1} key={index}>
                  {columns.map((column) => {
                    const value = row[column.dataIndex as keyof T];
                    return (
                      <TableCell key={column.key}>
                        {renderCellContent(value, row, column)}
                      </TableCell>
                    );
                  })}
                </TableRow>
              ))
            )}
          </TableBody>
        </Table>
      </TableContainer>
      {pagination && (
        <TablePagination
          rowsPerPageOptions={[10, 25, 100]}
          component="div"
          count={pagination.total}
          rowsPerPage={pagination.pageSize}
          page={pagination.current - 1}
          onPageChange={(_: React.MouseEvent<HTMLButtonElement> | null, newPage: number) => pagination.onChange(newPage + 1, pagination.pageSize)}
          onRowsPerPageChange={(event) =>
            pagination.onChange(1, parseInt(event.target.value, 10))
          }
        />
      )}
    </Paper>
  );
} 